from django.conf import settings
from django.core.mail.backends.smtp import EmailBackend
import smtplib

class EmailBackend(EmailBackend):
	def __init__(self, host=None, port=None, username=None, password=None,
                 use_tls=None, fail_silently=False, **kwargs):
		if not host:
			host = settings.EMAIL_HOST
		if not username:
			username = settings.EMAIL_HOST_USER
		if not password:
			password = settings.EMAIL_HOST_PASSWORD
		self.server = smtplib.SMTP()
		self.server.connect(host)
		self.server.login(str(username), str(password))

	def open(self):
		pass
	
	def close(self):
		pass

	def send_messages(self, email_messages):
		if not email_messages:
			return
		num_sent = 0
		for message in email_messages:
			sent = self._send(message)
			if sent:
				num_sent += 1
		return num_sent

	def _send(self, email_message):
		self.server.sendmail(email_message.from_email, email_message.recipients(), email_message.message().as_string())

